import imaplib
import email
from snarl import showNotification
from snarl import registerSnarl
import pickle
import gmailConfig

olduid = 123
try:
    #try to load the last UID seen
    olduid = pickle.load(open(gmailConfig.pickleFile,'rb'))
    print 'found pickle file'
except IOError:
    #file doesn't exist
    olduid = -1
    print "pickle file didn't exist"

#connect to gmail
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(gmailConfig.userName,gmailConfig.password)
mail.select(gmailConfig.folder2Watch,readonly=True)

#get all messages from the inbox
if olduid != -1:
    result, data = mail.uid('search',None,'(UID '+str(olduid)+':*)')
else:
    result, data = mail.uid('search',None,'ALL')
#get the actual message UIDs
messages = data[0].split()

#make sure we're registered with Snarl
registerSnarl()

#save the last UID to the pickle file
#this is the one to start with next time we run
pickle.dump(messages[-1],open(gmailConfig.pickleFile,'wb'))

if olduid == -1:
    print "First time.  I'm not gonna print all your messages, dude.  I'll tell you when you get new mail"
else:
    x = len(messages)-1
    #loop while the UID is not the UID seen last time we ran
    while True:
        uid = messages[x]
        print uid
        #break if we see what we've seen before
        if uid == olduid:
            break
        #otherwise, decrement the array index
        else:
            x = x-1

        #fetch
        result,data = mail.uid('fetch',uid,'(RFC822)')

        #get raw email data
        raw = data[0][1]

        #convert raw to email
        msg = email.message_from_string(raw)

        #tell Snarl we got a new email
        #title is the 'From' email
        #content is the email subject
        showNotification(msg['from'],msg['subject'],'https://mail.google.com/mail/u/0/#inbox')

    mail.logout()
